package cn.iocoder.yudao.module.promotion.coupon.dal.mysql;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.mapper.CoreMapper;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.api.promotion.coupon.enums.CouponTakeTypeEnum;
import cn.iocoder.yudao.module.api.promotion.coupon.enums.CouponTemplateValidityTypeEnum;
import cn.iocoder.yudao.module.promotion.coupon.dal.dataobject.CouponTemplateDO;
import cn.iocoder.yudao.module.promotion.coupon.vo.CouponTemplatePageReqVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

/**
 * 优惠劵模板 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface CouponTemplateMapper extends CoreMapper<CouponTemplateDO> {

    default PageResult<CouponTemplateDO> selectPage(CouponTemplatePageReqVO reqVO) {
        // 构建可领取的查询条件
        Consumer<LambdaQueryWrapper<CouponTemplateDO>> canTakeConsumer = buildCanTakeQueryConsumer(reqVO.getCanTakeTypes());
        // 执行分页查询
        return selectPage(reqVO, new CoreLambdaQueryWrapper<CouponTemplateDO>()
                .likeIfPresent(CouponTemplateDO::getName, reqVO.getName())
                .eqIfPresent(CouponTemplateDO::getStatus, reqVO.getStatus())
                .eqIfPresent(CouponTemplateDO::getDiscountType, reqVO.getDiscountType())
                .betweenIfPresent(CouponTemplateDO::getCreateTime, reqVO.getCreateTime())
                .eqIfPresent(CouponTemplateDO::getProductScope, reqVO.getProductScope())
                .and(reqVO.getProductScopeValue() != null, w -> w.apply("FIND_IN_SET({0}, product_scope_values) > 0",
                        reqVO.getProductScopeValue()))
                .and(canTakeConsumer != null, canTakeConsumer)
                .orderByDesc(CouponTemplateDO::getId));
    }

    default int updateTakeCount(Long id, Integer incrCount) {
        LambdaUpdateWrapper<CouponTemplateDO> updateWrapper = new LambdaUpdateWrapper<CouponTemplateDO>()
                .eq(CouponTemplateDO::getId, id)
                .setSql("take_count = take_count + " + incrCount);
        // 增加已领取的数量（incrCount 为正数），需要考虑发放数量 totalCount 的限制
        if (incrCount > 0) {
            updateWrapper.and(i -> i.apply("take_count < total_count")
                    .or().eq(CouponTemplateDO::getTotalCount, CouponTemplateDO.TOTAL_COUNT_MAX));
        }
        return update(updateWrapper);
    }

    default List<CouponTemplateDO> selectListByTakeType(Integer takeType, @Nullable Integer status) {
        CoreLambdaQueryWrapper<CouponTemplateDO> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.eq(CouponTemplateDO::getTakeType, takeType);
        wrapper.eqIfPresent(CouponTemplateDO::getStatus, status);
        return selectList(wrapper);
    }

    default List<CouponTemplateDO> selectList(List<Integer> canTakeTypes, Integer productScope, Long productScopeValue, Integer count) {
        // 构建可领取的查询条件
        Consumer<LambdaQueryWrapper<CouponTemplateDO>> canTakeConsumer = buildCanTakeQueryConsumer(canTakeTypes);
        CoreLambdaQueryWrapper<CouponTemplateDO> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.eqIfPresent(CouponTemplateDO::getProductScope, productScope);
        wrapper.and(productScopeValue != null, w -> w.apply("FIND_IN_SET({0}, product_scope_values) > 0",
                productScopeValue));
        wrapper.and(canTakeConsumer != null, canTakeConsumer);
        wrapper.limitN(count);
        wrapper.orderByDesc(CouponTemplateDO::getId);
        return selectList(wrapper);
    }

    static Consumer<LambdaQueryWrapper<CouponTemplateDO>> buildCanTakeQueryConsumer(@Nonnull List<Integer> canTakeTypes) {
        Consumer<LambdaQueryWrapper<CouponTemplateDO>> canTakeConsumer = null;
        if (CollUtil.isNotEmpty(canTakeTypes)) {
            canTakeConsumer = w ->
                    w.eq(CouponTemplateDO::getStatus, CommonStatusEnum.ENABLE.getStatus()) // 1. 状态为可用的
                            .in(CouponTemplateDO::getTakeType, canTakeTypes) // 2. 领取方式一致
                            .and(ww -> ww.gt(CouponTemplateDO::getValidEndTime, LocalDateTime.now())  // 3.1 未过期
                                    .or().eq(CouponTemplateDO::getValidityType, CouponTemplateValidityTypeEnum.TERM.getType())) // 3.2 领取之后
                            .apply(" (take_count < total_count OR total_count = -1)"); // 4. 剩余数量大于 0，或者无限领取
        }
        return canTakeConsumer;
    }

    default List<CouponTemplateDO> selectCanTakeListByShopId(Long shopId) {
        if (shopId == null || shopId <= 0) {
            return CollUtil.newArrayList();
        }
        List<Integer> canTakeTypes = CollUtil.newArrayList(CouponTakeTypeEnum.USER.getType(), CouponTakeTypeEnum.REGISTER.getType());
        Consumer<LambdaQueryWrapper<CouponTemplateDO>> canTakeConsumer = buildCanTakeQueryConsumer(canTakeTypes);
        return selectList(new CoreLambdaQueryWrapper<CouponTemplateDO>()
                .eqIfPresent(CouponTemplateDO::getShopId, shopId)
                .and(canTakeConsumer != null, canTakeConsumer));
    }

    default List<CouponTemplateDO> selectCanTakeListByShopIds(Set<Long> shopIds) {
        if (CollUtil.isEmpty(shopIds)) {
            return CollUtil.newArrayList();
        }
        List<Integer> canTakeTypes = CollUtil.newArrayList(CouponTakeTypeEnum.USER.getType(), CouponTakeTypeEnum.REGISTER.getType());
        Consumer<LambdaQueryWrapper<CouponTemplateDO>> canTakeConsumer = buildCanTakeQueryConsumer(canTakeTypes);
        return selectList(new CoreLambdaQueryWrapper<CouponTemplateDO>()
                .inIfPresent(CouponTemplateDO::getShopId, shopIds)
                .and(canTakeConsumer != null, canTakeConsumer));
    }

}
